<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018\11\28 0028
 * Time: 9:30
 */
class MongoModel
{
    private $config;
    private $client;

    public function __construct()
    {
        //mongodb://127.0.0.1:27017/admin:admin
        $this->config = "mongodb://127.0.0.1:27017";
        $this->client = new MongoDB\Driver\Manager($this->config);
    }

    /**
     * 添加数据
     * @param $document
     * @param $namespace
     * @return bool
     */
    public function add($document, $namespace)
    {
        $bulk = new MongoDB\Driver\BulkWrite;
        //$document = ['_id' => new MongoDB\BSON\ObjectID, 'name' => 'content_id', 'id' => 1];

        $bulk->insert($document);

        $writeConcern = new MongoDB\Driver\WriteConcern(MongoDB\Driver\WriteConcern::MAJORITY, 1000);
        $result = $this->client->executeBulkWrite($namespace, $bulk, $writeConcern);
        return $result ? true : false;
    }

    /**
     * 更新数据
     * @param $filter
     * @param $update
     * @param $options
     * @param $namespace
     * @return bool
     */
    public function update($filter, $update, $options, $namespace)
    {
        $bulk = new MongoDB\Driver\BulkWrite;
        $bulk->update($filter, $update, $options);

        $writeConcern = new MongoDB\Driver\WriteConcern(MongoDB\Driver\WriteConcern::MAJORITY, 1000);
        $result = $this->client->executeBulkWrite($namespace, $bulk, $writeConcern);
        return $result ? true : false;
    }

    /**
     * 删除数据
     * @param $filter
     * @param $options
     * @param $namespace
     */
    public function delete($filter, $options, $namespace)
    {
        $bulk = new MongoDB\Driver\BulkWrite;
        $bulk->delete($filter, $options);
        //$bulk->delete(['x' => 1], ['limit' => 1]);   // limit 为 1 时，删除第一条匹配数据
        //$bulk->delete(['x' => 2], ['limit' => 0]);   // limit 为 0 时，删除所有匹配数据

        $writeConcern = new MongoDB\Driver\WriteConcern(MongoDB\Driver\WriteConcern::MAJORITY, 1000);
        $result = $this->client->executeBulkWrite($namespace, $bulk, $writeConcern);
    }

    /**
     * 查询数据
     * @param $filter
     * @param $options
     * @param $namespace
     * @return \MongoDB\Driver\Cursor
     * @throws \MongoDB\Driver\Exception\Exception
     */
    public function select($filter, $options, $namespace)
    {
        $query = new MongoDB\Driver\Query($filter, $options);
        $cursor = $this->client->executeQuery($namespace, $query);
        $result = [];
        foreach ($cursor as $v) {
            $result[] = $v;
        }
        return $result;
    }

}